
# -*- coding: utf-8 -*-
import os
import sys
import csv
import matplotlib.pyplot as plt
from matplotlib.figure import SubplotParams

from alenz_0080_script2 import Sahel


"""import precipitation values as list"""
data = csv.reader(open('alenz_0080_precip.csv', 'rb'), delimiter=';')
dataImport = []
dataImport.extend(data)
precip = []


class SoilQuality(Sahel):
    
    def __init__(self, population, birthRate, deathRate, timeStep, timeRange,\
                 capacity):
        """Calculate soil quality.
        
        Methods:
        birth -- soil regeneration
        death -- soil degradation
        
        """
        Sahel.__init__(self, population, birthRate, deathRate, timeStep,\
                       timeRange)
        self.capacity = capacity
        
    def birth(self):
        """Calculate soil regeneration, use capacity and encounter 'landUse'"""
        return ((self.capacity - self.population[len(self.population) - 1])\
                / self.capacity) * landUse * self.timeStep

    def death(self):
        """Calculate soil degradation, use encounter 'soilUse'"""
        return soilUse * self.timeStep


class Food(Sahel):
    
    def __init__(self, population, birthRate, deathRate, timeStep, timeRange):
        """Calculate amount of food.
        
        Methods:
        birth -- food growth
        death -- food decline
        
        """
        Sahel.__init__(self, population, birthRate, deathRate, timeStep,\
                       timeRange)
           
    def birth(self):
        """Calculate food growth, use encounter 'soilUse'"""
        return self.birthRate * soilUse * self.timeStep

    def death(self):
        """Calculate food decline, use encounter 'consumption'"""
        return consumption * self.timeStep


class Human(Sahel):
   
    def __init__(self, population, birthRate, deathRate, timeStep, timeRange):
        """Calculate human population.
        
        Methods:
        birth -- births
        death -- deaths
        
        """
        Sahel.__init__(self, population, birthRate, deathRate, timeStep,\
                       timeRange)
        
    def birth(self):
        """Calculate births, use encounter 'consumption'"""
        return consumption * self.birthRate * self.timeStep

    def death(self):
        """Calculate deaths"""
        return self.population[len(self.population) - 1] * self.deathRate\
               * self.timeStep


"""Set initials for above classes"""
humanPop = Human (50, 0.6, 0.1, 0.005, 50)
foodPop = Food (100, 0.5, 0.25, 0.005, 50)  # deathRate not used
soilPop = SoilQuality (50, 0.5, 0.1, 0.005, 50, 100)  # birthRate and deathRate
                                                      # not used in calculations

"""set initials for encounters"""
consumption = 1  # 'encounter' of food and humans
landUse = 1  # 'encounter' of soil and humans
soilUse = 1  # 'encounter' of soil and food


"""set variables used in calculations of encounters"""
consumers = 0.003  # stress on food, induced by people
growthStress = 0.005  # stress on soil, induced by food 
stress = 0.001  # stress on soil, induced by people


i = 0
while i < soilPop.timeRange / soilPop.timeStep:

    """Transcribe strings on list 'dataImport' into integers on list 'precip'"""
    x = dataImport[i]
    precipData = int(dataImport[i][0])
    precip.append(precipData)

    """
    Set treshold for positive/negative influence of precipitation on soil
    regeneration
    """
    if precip[i] >= 150:
        precipFactor = 0.1
    else:
        precipFactor = -0.1

    precipIntensity = precipFactor * precipData
    
    """Calculate soil quality, amount of food and population"""
    soilPopSim = soilPop.getPop() + soilPop.birth() - soilPop.death()
    foodPopSim = foodPop.getPop() + foodPop.birth() - foodPop.death()
    humanPopSim = humanPop.getPop() + humanPop.birth() - humanPop.death()
    
    """Calculate encounters"""
    consumption = foodPopSim * humanPopSim * consumers
    landUse = soilPopSim * humanPopSim * stress * precipIntensity
    soilUse = foodPopSim * soilPopSim * growthStress
    
    """Append calculated values to list 'population'"""
    soilPop.population.append(soilPopSim)
    foodPop.population.append(foodPopSim)
    humanPop.population.append(humanPopSim)
    
    i = i + 1


"""Print initials"""
print ' '
print 'INITIAL:'
print '=' * 15
print 'timeRange:', soilPop.timeRange
print 'timeStep:', soilPop.timeStep
print ' '
print 'precipFactor:', precipFactor
print 'consumers:', consumers
print 'growthStress:', growthStress
print 'stress:', stress
print ' '
print 'soilPop:', soilPop.population[0]
print 'foodPop:', foodPop.population[0], ',', foodPop.birthRate, ',',\
      foodPop.deathRate
print 'humanPop:', humanPop.population[0], ',', humanPop.birthRate, ',',\
      humanPop.deathRate
print ' '

"""Print calculated time series"""
print 'TIME SERIES:'
print '=' * 15
i = 0
while i < soilPop.timeRange/soilPop.timeStep:
    #print 'Year', i * soilPop.timeStep, ' SoilQuality:', soilPop.population[i],\
       #   ' Food:', foodPop.population[i], ' Human:', humanPop.population[i]
    i = i + 1
print '=' * 80


"""Plot time series"""
def results_plot(ax, fontsize = 11):
    ax1.plot(precip)
    ax1.plot(soilPop.population)
    ax1.plot(foodPop.population)
    ax1.plot(humanPop.population)

    ax1.set_xlabel('years', fontsize = 14)
    ax1.set_title ('TIME SERIES', fontsize = 17)

    ax1.set_xticks((1000, 2000, 3000, 4000, 5000, 6000,\
                    7000, 8000, 9000, 10000))  # default scale
    labelsx = ax1.set_xticklabels((5, 10, 15, 20,\
                                   25, 30, 35, 40, 45, 50))  # new scale

    ax1.legend(('precipitation [mm/year]', 'soil quality [0 - 100]',\
                'food [t * 10^3]', 'human population [M]'))

fig, ((ax1))= plt.subplots(nrows = 1, ncols = 1)
results_plot(ax1)
plt.show()

